package com.example.demo.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.SecureUtil;
import com.example.demo.entity.admin_users;
import com.example.demo.mapper.admin_users_mapper;
import com.example.demo.util.APIResultUtil;
import com.example.demo.util.JWTUtil;
import com.example.demo.util.LogUtil;
import com.example.demo.util.SqlSessionUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/api")
public class UsersApi {

    //  用户登录(开发完成)
    @RequestMapping("/userLogin")
    public Object userLogin(@Param("email") String email, @Param("password") String password) {
        SqlSession sqlSession = null;
        try {
//        首先判断用户是否存在
            sqlSession = SqlSessionUtil.GetSession();
            admin_users_mapper mapper = sqlSession.getMapper(admin_users_mapper.class);
            admin_users userByEmail = mapper.getUserByEmail(email);
            if (userByEmail != null) {
//               如果存在
                //如果存在就校验用户密码是否匹配
                if (userByEmail.getPassword().equals(SecureUtil.md5(password))) {
                    //如果匹配就返回Tooken(JWT)
                    String token = JWTUtil.getToken(userByEmail.getEmail(), 600);
//                    修改用户最后登录时间
                    mapper.updateLastLogin(email);
                    sqlSession.commit();
                    LogUtil.INFO("登录提醒","电子邮箱:"+email+"于"+ DateTime.now()+"登录系统");
//                    数据打包Object类型
                    HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("username",userByEmail.getUsername());
                    objectObjectHashMap.put("email",userByEmail.getEmail());
                    objectObjectHashMap.put("token",token);
                    return APIResultUtil.apiResult(true, "欢迎回来：" + userByEmail.getUsername(), objectObjectHashMap);
                } else {
                    LogUtil.INFO("登录提醒","电子邮箱:"+email+"于"+ DateTime.now()+"登录失败");
                    return APIResultUtil.apiResult(false, "密码错误,请重试", null);
                }
            } else {
//                如果不存在
                return APIResultUtil.apiResult(false, "用户不存在，请注册", null);
            }
        } catch (Exception e) {
            LogUtil.error("UserApi_userLogin用户登录异常", e.getMessage());
            return APIResultUtil.apiResult(false, "系统异常,请联系管理员", null);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    // 新增用户(开发完成)
    @RequestMapping("/addUser")
    public Object addUser(@Param("username") String username, @Param("password") String password, @Param("email") String email, @Param("phone") String phone) {
        SqlSession sqlSession = null;
        try {
            // 调用SqlSession
            sqlSession = SqlSessionUtil.GetSession();
            admin_users_mapper mapper = sqlSession.getMapper(admin_users_mapper.class);
//            查询用户是否存在
            admin_users userByEmail = mapper.getUserByEmail(email);
            if(userByEmail == null){
                // 创建新的用户对象并设置属性
                admin_users newUser = new admin_users();
                newUser.setUsername(username);
                newUser.setPassword(SecureUtil.md5(password)); // 加密密码
                newUser.setEmail(email);
                newUser.setPhone(phone);
                newUser.setStatus("active");
                newUser.setRole("user");

                if (mapper.addUser(newUser) >= 1) {
                    sqlSession.commit();
                    return APIResultUtil.apiResult(true, "用户：" + username + "添加成功", null);
                } else {
                    throw new IllegalArgumentException("添加用户时出错");
                }
            }else{
                return APIResultUtil.apiResult(false, "邮箱已存在,请登录", null);
            }
        } catch (Exception e) {
            LogUtil.error("UserApi_addUser新增用户异常", e.getMessage());
            return APIResultUtil.apiResult(false, "系统异常,请联系管理员", null);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    // 通过邮箱查询用户信息(开发完成)
    @RequestMapping("/getUserByEmail")
    public Object getUserByEmail(@Param("email") String email) {
        SqlSession sqlSession = null;
        try {
            // 调用SqlSession
            sqlSession = SqlSessionUtil.GetSession();
            admin_users_mapper mapper = sqlSession.getMapper(admin_users_mapper.class);
            admin_users user = mapper.getUserByEmail(email);
            if (user != null) {
                return APIResultUtil.apiResult(true, "查询成功", user);
            } else {
                return APIResultUtil.apiResult(false, "用户不存在", null);
            }

        } catch (Exception e) {
            LogUtil.error("UserApi_getUserByEmail查询异常", e.getMessage());
            return APIResultUtil.apiResult(false, "系统异常,请联系管理员", null);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    // 修改用户信息
    @RequestMapping("/updateUser")
    public Object updateUser(@RequestBody admin_users user) {
        SqlSession sqlSession = null;
        try {
            // 调用SqlSession
            sqlSession = SqlSessionUtil.GetSession();
            admin_users_mapper mapper = sqlSession.getMapper(admin_users_mapper.class);
            if (mapper.updateUser(user) >= 1) {
                sqlSession.commit();
                return APIResultUtil.apiResult(true, "用户信息更新成功", null);
            } else {
                throw new IllegalArgumentException("更新用户信息时出错");
            }
        } catch (Exception e) {
            LogUtil.error("UserApi_updateUser修改用户信息异常", e.getMessage());
            return APIResultUtil.apiResult(false, "系统异常,请联系管理员", null);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    // 删除用户(开发完成)
    @RequestMapping("/deleteUser")
    public Object deleteUser(@Param("email") String email) {
        SqlSession sqlSession = null;
        try {
            // 调用SqlSession
            sqlSession = SqlSessionUtil.GetSession();
            admin_users_mapper mapper = sqlSession.getMapper(admin_users_mapper.class);
//            判断用户是否存在
            if(mapper.getUserByEmail(email) != null){
                if (mapper.deleteUser(email) >= 1) {
                    sqlSession.commit();
                    return APIResultUtil.apiResult(true, "用户删除成功", null);
                } else {
                    throw new IllegalArgumentException("删除用户时出错");
                }
            }else{
                return APIResultUtil.apiResult(false, "用户不存在", null);
            }
        } catch (Exception e) {
            LogUtil.error("UserApi_deleteUser用户删除异常", e.getMessage());
            return APIResultUtil.apiResult(false, "系统异常,请联系管理员", null);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}